export default {
  async fetch(request, env, ctx) {
    const kv = env.KV
    const url = new URL(request.url)
    const pathname = url.pathname;
    if (request.method == 'POST' && pathname == '/update-all-nodes') {
      const res=await request.text()
      const data=Object.fromEntries(res.trim().replace(/\n/g,'').split(';').map(n=>n.split('=')))
      let nodes=data['node'].split(',')
      let _info = await kv.get('node_info')
      let info=JSON.parse(_info);
      for(let node of nodes){
        let key=node.includes('serv00')?'serv00':'ct8';
        info[key].host=node;
      }
      let result=JSON.stringify(info)
      await kv.put('node_info',result)
      // const allow_keys = ['id', 'node', 'info']
      // for (let key in data) {
      //   if (allow_keys.includes(key)) {
      //     await kv.put(key, data[key])
      //   }
      // }
      // return new Response(JSON.stringify(data))
      return Response.json(info)
    }
    if (pathname == '/getid') {
      const id = await kv.get('id')
      return new Response(id)
    }
    if (pathname == '/getnode') {
      let _info = await kv.get('node_info')
      let info=JSON.parse(_info);
      let host=[info['ct8'].host,info['serv00'].host]
      return Response.json(host)
    }
    if(pathname=='/running'){
      let _info = await kv.get('node_info')
      let info=JSON.parse(_info);
      let host=[info['ct8'].host,info['serv00'].host]
      return new Response(host.join(','))
    }
    if(pathname=='/gethost'){
      var serv00=await kv.get('serv00')
      var ct8=await kv.get('ct8')
      serv00=serv00.trim().split('\n')
      ct8=ct8.trim().split('\n')
      let host=[]
      let random=~~(Math.random()*serv00.length)
      host.push(serv00[random])
      random=~~(Math.random()*ct8.length)
      host.push(ct8[random])
      return new Response(host.join(','))
    }

    /*测试时清除无效key
    if (pathname == '/del') {
      const keys = await env.KV.list();
      keys.keys.forEach(key => kv.delete(key.name));
    }
    */


    const page = await kv.get('errpage')
    return new Response(page,{
      headers: { 'Content-Type': 'text/html;charset=utf-8' }
    });
  },
};